package com.wwdx.controller.rest;

import com.google.common.collect.Maps;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.*;
import com.wwdx.model.dto.BaseActivityDTO;
import com.wwdx.model.dto.BaseUserInfoDTO;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

/**
 * @author liguoliang
 */
@RestController
@RequestMapping("order")
@Api(tags = "活动接口")
public class RestOrderController extends BaseController{

    /**
     * 查询赠一得一
     * @param unionid 领取人
     * @param unionid2 分享人
     * @param bookid 书籍
     */
    @RequestMapping("/getgiveone")
    @ApiOperation(value = "查询赠一得一",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unionid",value = "领取人",required = true),
            @ApiImplicitParam(name = "unionid2",value = "分享人",required = true),
            @ApiImplicitParam(name = "bookid",value = "书籍ID",required = true)
    })
    public ResultBean getgiveone(String unionid, String unionid2, Long bookid){
        String key = String.format(ConstantHolder.GIVEONE_USER_LIST, unionid);
        Integer isorder = wwdxOrderService.isorder(bookid, unionid);
        BaseUserInfoDTO.GiveOneUserInfoDTO userInfoDTO = (BaseUserInfoDTO.GiveOneUserInfoDTO) valueOperations.get(String.format(ConstantHolder.GIVEONE_USER_OBJ,unionid2,bookid));
        //未领取
        String flag = bookid.toString();
        //已购买
        String qrcode2 = bookid + Boolean.TRUE.toString();
        //已领取
        String qrcode3 = bookid + Boolean.FALSE.toString();
        //领取书籍数量
        Long size = setOperations.size(key);
        if (userInfoDTO == null){
            if (isorder == 1){
                flag = qrcode2;
            }else if (size >= 1) {
                flag = qrcode3;
            }
        }else {
            if (unionid.equals(userInfoDTO.getUnionid())){
                flag = bookid.toString();
            }else if (isorder == 1){
                flag = qrcode2;
            }else {
                flag = qrcode3;
            }
        }
        Map<String, Object> map = Maps.newHashMapWithExpectedSize(4);
        map.put("isbook",setOperations.isMember(String.format(ConstantHolder.GIVEONE_USER_BOOK_SET,unionid2), String.valueOf(bookid)));
        map.put("count",size);
        map.put("isorder",isorder);
        //二维码
        BaseActivityDTO.GiveOneBusinessDTO dto = BaseActivityDTO.GiveOneBusinessDTO.builder().
                unionid(unionid).bookFlag(flag).channel(ConstantHolder.Constant.WEIXIN).
                unionid2(unionid2).bookid(bookid).build();
        hashOperations.put(ConstantHolder.GIVEONE_UNIONID_MAP,unionid,dto);
        String qrCode = wechatPublishService.getQrcodeUrl(flag,miDuWxService);
        map.put("qrcode",qrCode);
        map.put("userInfo",userInfoDTO);
        return renderSuccess(map);
    }

    /**
     * 保存赠一得一
     */
    @RequestMapping("/savegiveone")
    @ApiOperation(value = "保存赠一得一",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unionid",value = "领取人",required = true),
            @ApiImplicitParam(name = "unionid2",value = "分享人",required = true),
            @ApiImplicitParam(name = "bookid",value = "书籍ID",required = true),
            @ApiImplicitParam(name = "channel",value = "渠道",required = true)
    })
    public ResultBean savegiveone(BaseActivityDTO.GiveOneBusinessDTO dto){
        String unionid = dto.getUnionid();
        if (unionid.equalsIgnoreCase(dto.getUnionid2())){return renderSuccess();}
        //领取人最多可领取一本书籍
        String key = String.format(ConstantHolder.GIVEONE_USER_LIST, unionid);
        long size = setOperations.size(key);
        int length = 1;
        if (size >= length){
            return renderError("超出领取数量");
        }
        //查询分享人是否关注公众号
        String appId = miDuWxService.getWxMpConfigStorage().getAppId();
        WwdxWeixinUserModel wwdxWeixinUserModel = wwdxWeixinUserService.getByUnionId(appId, unionid);
        if (wwdxWeixinUserModel == null){
            return renderError("领取人未关注");
        }
        //保存赠一得一订单
        payService.executeGiveoneOrder(dto);
        return renderSuccess();
    }

    /**
     * 兑换码兑换产品
     * @param cdkey 兑换码
     * @param channel 渠道
     */
    @RequestMapping("/cdkey")
    @ApiOperation(value = "兑换码兑换",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "cdkey",value = "兑换码",required = true),
            @ApiImplicitParam(name = "channel",value = "渠道",required = true)
    })
    public ResultBean cdkey(String token, String sign, String cdkey, String channel) {
        SortedMap<String, Object> sortedMap = super.getSortedMap(token,sign);
        sortedMap.put("cdkey", cdkey);
        sortedMap.put("channel", channel);
        ResultBean resultBean = super.validSignTokenResult(sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String msg;
        WwdxCdKeyModel wwdxCdKeyModel = wwdxCdKeyService.getByCdKey(cdkey);
        if (wwdxCdKeyModel == null){
            msg = "兑换码不存在";
            return renderError(msg);
        }
        if (wwdxCdKeyModel.getStatus() == 1){
            msg = "兑换码已经被使用";
            return renderError(msg);
        }
        String unionId = (String) resultBean.getData();
        Long productId = wwdxCdKeyModel.getProduct_id();
        //修改兑换码的状态
        wwdxCdKeyModel.setStatus(1);
        wwdxCdKeyModel.setUnionid(unionId);
        wwdxCdKeyModel.setChannel(channel);
        wwdxCdKeyModel.setExchange_time(new Date());
        wwdxCdKeyService.update(wwdxCdKeyModel);
        Integer type = wwdxCdKeyModel.getType();
        //订单记录
        WwdxOrderModel wwdxOrderModel = WwdxOrderModel.builder().price(new BigDecimal(0)).orderno(makeOrderNum())
                .channel(channel).product_id(productId).type(type).unionid(unionId)
                .createTime(new Date()).payTime(new Date()).payType(ConstantHolder.Constant.CDKEY_PAYTYPE).status(1).build();
        wwdxOrderService.save(wwdxOrderModel);
        //7会员兑换码
        if (type == ConstantHolder.Constant.VIPTYPE){
            payService.vipRecharge(unionId,productId);
        }else {
            //将已购买数据写入缓存
            taskExecutor.execute(()-> wwdxOrderService.purchase(unionId,productId,type));
        }
        return renderSuccess(type);
    }

    /**
     * 查询优惠卷
     */
    @RequestMapping("/get/coupon")
    @ApiOperation(value = "查询优惠卷",httpMethod = "GET")
    public ResultBean searchcoupon(){
        return renderSuccess(wwdxCouponService.list());
    }

    /**
     * 领取优惠卷
     */
    @RequestMapping("/receive/coupon")
    @ApiOperation(value = "领取优惠卷",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true)
    })
    public ResultBean getcoupon(String token, String sign){
        SortedMap<String, Object> sortedMap = super.getSortedMap(token,sign);
        ResultBean resultBean = super.validSignTokenResult(sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String unionId = (String) resultBean.getData();
        List<WwdxCouponModel> wwdxCouponModels = wwdxCouponService.list();
        String msg;
        if (CollectionUtils.isEmpty(wwdxCouponModels)){
            msg = "未找到可用优惠卷";
            return renderError(msg);
        }
        WwdxCouponModel wwdxCouponModel = wwdxCouponModels.get(0);
        List<WwdxCouponLogModel> list = wwdxCouponLogService.list(unionId,null);
        if (list.size() >= wwdxCouponModel.getNum()){
            msg = "优惠券领取超出上限";
            return renderError(msg);
        }
        WwdxCouponLogModel model = WwdxCouponLogModel.builder().name(wwdxCouponModel.getName())
                .unionid(unionId).status(0).price(wwdxCouponModel.getPrice()).gmtCreated(wwdxCouponModel.getExpires()).build();
        wwdxCouponLogService.save(model);
        return renderSuccess();
    }

    /**
     * 查询用户优惠卷
     */
    @RequestMapping("/user/coupon")
    public void usercoupon(String token, String sign){
        /*ResultBean resultBean = super.validSignTokenResult(super.getSortedMap(token,sign));
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String unionId = (String) resultBean.getData();
        return renderSuccess(wwdxCouponLogService.list(unionId,null));*/
    }
}